package mimipost.database;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.annotation.Resource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class Database implements Serializable {
	private static final long serialVersionUID = -125548702354016043L;
	
	public Database() {
		try {
			initConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Initialize datasource and connection
	 * @throws SQLException
	 */
	private void initConnection() throws SQLException {
		try {
			Context ctx = new InitialContext();
			dataSource = (DataSource) ctx
					.lookup("java:comp/env/jdbc/minipost");			
		} catch (NamingException e) {
			//e.printStackTrace();
			dataSource = null;
			connection = null;
		}
		if ( dataSource != null ) {
			connection = dataSource.getConnection();
		}
		
		if ( connection == null ) {
			loadConnection();
		}
	}
	
	/**
	 *  如果无法加载数据源，则通过驱动进行数据库连接
	 */
	private void loadConnection() {		
		String driverName = "com.mysql.jdbc.Driver";		// 加载JDBC驱动
		// 连接服务器和数据库minipost
		String url =  "jdbc:mysql://localhost:3306/minipost?useUnicode=true&amp;characterEncoding=UTF-8";
		//String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";		// 加载JDBC驱动
		//String url =  "jdbc:sqlserver://localhost:1433; DatabaseName=student";	 // 连接服务器和数据库student

		String userName = "root"; 	// 默认用户名
		String userPwd = ""; 		// 密码

		try {
			Class.forName(driverName);  //加载JDBC驱动程序
			connection = DriverManager.getConnection(url, userName, userPwd);
			//System.out.println("Connection Successful!"); // 如果连接成功
			// 控制台输出Connection Successful!
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Resource injection.
	 */
	@Resource(name="jdbc/minipost")
	private DataSource dataSource;
	public Connection connection;
}
